/*
 * Gui.java
 *
 * Created on December 9, 2007, 12:21 PM
 */

package net.sourceforge.jtocr;

import java.awt.Cursor;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEditSupport;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.DGT.OCRAdjuntosCorreo.AlertasLN;
import com.DGT.OCRAdjuntosCorreo.DictionaryWord;
import com.DGT.OCRAdjuntosCorreo.LectorCorreoAdjuntos;
import com.DGT.OCRCAjuntosCorreo.Utils.*;

/**
 *
 * @author  Quan Nguyen (nguyenq@users.sf.net)
 *
 */
public class Gui extends javax.swing.JFrame {
//    private File imageFile;
    public static final String APP_NAME = "OCR_DGT";
    final static boolean MAC_OS_X = System.getProperty("os.name").startsWith("Mac");
    private final String UTF8 = "UTF-8";
    protected ResourceBundle myResources;
//    protected final Preferences prefs = Preferences.userRoot().node("/net/sourceforge/jtocr");
    protected final Preferences prefs = Preferences.userRoot().node("tesseract");
    private Font font;
//    private final Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    private int imageIndex;
    private int imageTotal;
    private ArrayList<ImageIconScalable> imageList;
    public final String EOL = System.getProperty("line.separator");
    private String currentDirectory;
    private String tessPath;
    private Properties prop;
//    private String curLangCode="spa";//lenguaje espa�ol "spa"
    private String[] langCodes;
    private String[] langs;
//    private ImageIconScalable imageIcon;
    private boolean allPages;
//    private boolean reset;
//    private JFileChooser chooser;
    private boolean wordWrapOn;
    private String selectedInputMethod;
    private float originalProportion;
    private File directoryTemporalAdjuntos;
	private File filesource;
	private ArrayList<DictionaryWord> palabrasClaveEncontradas=new ArrayList<DictionaryWord>();
	static Logger logger=null;
	private Timer timer; 
    private File directoryEscaneos;
	   
 
	
	
    /**
     * Creates new form Gui
     */
    public Gui() {
    	
    	logger = Logger.getLogger(this.getClass().getName());
    	logger.info("Run Application OCR DGT");
    	tessPath = prefs.get("TesseractDirectory", System.getProperty("user.dir")+File.separator+"tesseract");
    	//tessPath = prefs.get("TesseractDirectory", new File("").getPath()+File.separator+"tesseract");
    	
        logger.info("TesseractDirectory: "+tessPath);
        
        try {
            prop = new Properties();
            FileInputStream fis = new FileInputStream("ISO639-3.xml");
            prop.loadFromXML(fis);
        }
        catch(Exception e){
        	logger.error("Error al abrir el archivo ISO639-3.xml"+e.getMessage());
        } 
            
        langCodes = new File(tessPath, "tessdata").list(new FilenameFilter() {
             public boolean accept(File dir, String name) {
             return name.endsWith(".inttemp");
             }
        });
        
/*
        
        File current=new File(System.getProperty("user.dir")+tessPath);
    	File[] archi=current.listFiles();
    	String g="";
    	for(File arch:archi){
    		g +=arch.getName()+"\n";	
    	}
    	logger.info("la carpeta "+tessPath+" preenta los siguientes archivos "+g);
    	logger.info("listando tesseract/tessdata");
		File tdata=new File(System.getProperty("user.dir")+tessPath+File.separator+"tessdata");
    	File[]tda=tdata.listFiles();
    	String tdas="";
    	for(File tdal:tda){
    		tdas+=tdal.getName()+"\n";
    	}
    	logger.info("la carpeta "+tdata+" contiene "+tdas);*/

        try{ 
            if (langCodes == null) {
                langs = new String[0];
            } else {
                langs = new String[langCodes.length];
            }
            for (int i = 0; i < langs.length; i++) {
                langCodes[i] = langCodes[i].replace(".inttemp", "");
                langs[i] = prop.getProperty(langCodes[i], langCodes[i]);
            }
        }
        catch(Exception e){
        	logger.error("Error "+e.getMessage());
       } 
      /*  } catch (IOException ioe) {
        	logger.error("Missing ISO639-3.xml file. Application aborts. ",ioe);
        } catch (Exception exc) {
        	logger.error(exc.getMessage());
        }*/
        
        selectedInputMethod = prefs.get("inputMethod", "Telex");
        
        try {
            UIManager.setLookAndFeel(prefs.get("lookAndFeel", UIManager.getSystemLookAndFeelClassName()));
        } catch (Exception e) {
            e.printStackTrace();
            // keep default LAF
        }
        
        initComponents();
        
        new DropTarget(this.jImageLabel, new ImageDropTargetListener(this));
        
        addWindowListener(
                new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                quit();
            }
            
            public void windowOpened(WindowEvent e) {
                setExtendedState(prefs.getInt("windowState", Frame.NORMAL));
            }
        });
        
        this.setTitle(APP_NAME);
        
        currentDirectory = prefs.get("currentDirectory", System.getProperty("user.home"));
//        chooser = new JFileChooser(currentDirectory);
//        chooser.setDialogTitle("Open Image File");
//        javax.swing.filechooser.FileFilter tiffFilter = new SimpleFilter("tif", "TIFF");
//        javax.swing.filechooser.FileFilter jpegFilter = new SimpleFilter("jpg", "JPEG");
//        javax.swing.filechooser.FileFilter gifFilter = new SimpleFilter("gif", "GIF");
//        javax.swing.filechooser.FileFilter pngFilter = new SimpleFilter("png", "PNG");
//        javax.swing.filechooser.FileFilter bmpFilter = new SimpleFilter("bmp", "Bitmap");
//        javax.swing.filechooser.FileFilter pdfFilter = new SimpleFilter("pdf", "PDF");
//        
//        chooser.addChoosableFileFilter(tiffFilter);
//        chooser.addChoosableFileFilter(jpegFilter);
//        chooser.addChoosableFileFilter(gifFilter);
//        chooser.addChoosableFileFilter(pngFilter);
//        chooser.addChoosableFileFilter(bmpFilter);
//        chooser.addChoosableFileFilter(pdfFilter);
//        
//        chooser.setFileFilter(chooser.getChoosableFileFilters()[prefs.getInt("filterIndex", 0)]);
//        
        myResources = ResourceBundle.getBundle("net.sourceforge.vietpad.Resources");
        
        wordWrapOn = prefs.getBoolean("wordWrap", false);
        jTextArea1.setLineWrap(wordWrapOn);
//        jCheckBoxMenuWordWrap.setSelected(wordWrapOn);
        
        font = new Font(
                prefs.get("fontName", MAC_OS_X ? "Lucida Grande" : "Tahoma"),
                prefs.getInt("fontStyle", Font.PLAIN),
                prefs.getInt("fontSize", 12));
        jTextArea1.setFont(font);
//        setSize(
//                snap(prefs.getInt("frameWidth", 500), 300, screen.width),
//                snap(prefs.getInt("frameHeight", 360), 150, screen.height));
//        setLocation(
//                snap(
//                prefs.getInt("frameX", (screen.width - getWidth()) / 2),
//                screen.x, screen.x + screen.width - getWidth()),
//                snap(
//                prefs.getInt("frameY", screen.y + (screen.height - getHeight()) / 3),
//                screen.y, screen.y + screen.height - getHeight()));
        
        if (langCodes == null) {      	
        	/*File carpeta=new File(tessPath+File.separator+"tessdata");
        	if(!carpeta.exists()&&!carpeta.isDirectory()){
        		logger.error("No existe el directorio "+tessPath+File.separator+"tessdata");
        	}
        	else{logger.error("Si existe el directorio "+tessPath+File.separator+"tessdata");}*/
        	logger.error("Tesseract is not found. Please specify its path in Settings menu."+langCodes);
        }
        
        populatePopupMenu();
        
        this.jTextArea1.getDocument().addUndoableEditListener(new RawListener());
        undoSupport.addUndoableEditListener(new SupportListener());
        m_undo.discardAllEdits();
        updateUndoRedo();
        updateCutCopyDelete(false);
    }
    
    void populatePopupMenu() {
        m_undoAction = new AbstractAction(myResources.getString("Undo")) {
            public void actionPerformed(ActionEvent e) {
                try {
                    m_undo.undo();
                } catch (CannotUndoException ex) {
                	logger.error("Unable to undo: " + ex);
                }
                updateUndoRedo();
            }
        };
        
        
        popup.add(m_undoAction);
        
        m_redoAction = new AbstractAction(myResources.getString("Redo")) {
            public void actionPerformed(ActionEvent e) {
                try {
                    m_undo.redo();
                } catch (CannotRedoException ex) {
                	logger.error("Unable to redo: " + ex);
                }
                updateUndoRedo();
            }
        };
        
        
        popup.add(m_redoAction);
        popup.addSeparator();
        
        actionCut = new AbstractAction(myResources.getString("Cut")) {
            public void actionPerformed(ActionEvent e) {
                jTextArea1.cut();
                updatePaste();
            }
        };
        
        popup.add(actionCut);
        
        actionCopy =  new AbstractAction(myResources.getString("Copy")) {
            public void actionPerformed(ActionEvent e) {
                jTextArea1.copy();
                updatePaste();
            }
        };
        
        
        popup.add(actionCopy);
        
        actionPaste = new AbstractAction(myResources.getString("Paste")) {
            public void actionPerformed(ActionEvent e) {
                undoSupport.beginUpdate();
                jTextArea1.paste();
                undoSupport.endUpdate();
            }
        };
        
        popup.add(actionPaste);
        
        actionDelete = new AbstractAction(myResources.getString("Delete")) {
            public void actionPerformed(ActionEvent e) {
                jTextArea1.replaceSelection(null);
            }
        };
        
        popup.add(actionDelete);
        popup.addSeparator();
        
        actionSelectAll = new AbstractAction(myResources.getString("Select_All"), null) {
            public void actionPerformed(ActionEvent e) {
                jTextArea1.selectAll();
            }
        };
        
        popup.add(actionSelectAll);
    }
    
    
    /**
     *  Updates the Undo and Redo actions
     */
    private void updateUndoRedo() {
        m_undoAction.setEnabled(m_undo.canUndo());
        m_redoAction.setEnabled(m_undo.canRedo());
    }
    
    
    /**
     *  Updates the Cut, Copy, and Delete actions
     *
     *@param  isTextSelected  whether any text currently selected
     */
    private void updateCutCopyDelete(boolean isTextSelected) {
        actionCut.setEnabled(isTextSelected);
        actionCopy.setEnabled(isTextSelected);
        actionDelete.setEnabled(isTextSelected);
    }
    
    /**
     *  Listens to raw undoable edits
     *
     */
    private class RawListener implements UndoableEditListener {
        /**
         *  Description of the Method
         *
         *@param  e  Description of the Parameter
         */
        public void undoableEditHappened(UndoableEditEvent e) {
            undoSupport.postEdit(e.getEdit());
        }
    }
    
    
    /**
     *  Listens to undoable edits filtered by undoSupport
     *
     */
    private class SupportListener implements UndoableEditListener {
        /**
         *  Description of the Method
         *
         *@param  e  Description of the Parameter
         */
        public void undoableEditHappened(UndoableEditEvent e) {
            m_undo.addEdit(e.getEdit());
            updateUndoRedo();
        }
    }
    
    
    /**
     *  Updates the Paste action
     */
    private void updatePaste() {
        try {
            Transferable clipData = clipboard.getContents(clipboard);
            if (clipData != null) {
                actionPaste.setEnabled(clipData.isDataFlavorSupported(DataFlavor.stringFlavor));
            }
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, APP_NAME
                    + myResources.getString("_has_run_out_of_memory.\nPlease_restart_") + APP_NAME
                    + myResources.getString("_and_try_again."), myResources.getString("Out_of_Memory"), JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        popup = new javax.swing.JPopupMenu();
//        jToolBar2 = new javax.swing.JToolBar();
//        jButtonOpen = new javax.swing.JButton();
//        jButtonOCR = new javax.swing.JButton();
//        jButtonClear = new javax.swing.JButton();
//        jPanel2 = new javax.swing.JPanel();
//        jLabel2 = new javax.swing.JLabel();
//        jComboBoxLang = new JComboBox(langs);
//        jComboBoxLang.setSelectedItem(prefs.get("langCode", null));
//        jSplitPane1 = new javax.swing.JSplitPane();
//        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
//        VietKeyListener keyLst = new VietKeyListener(jTextArea1);
//        jTextArea1.addKeyListener(keyLst);
//        VietKeyListener.setInputMethod(InputMethods.valueOf(selectedInputMethod));
//        VietKeyListener.setSmartMark(true);
//        VietKeyListener.consumeRepeatKey(true);
//        VietKeyListener.setVietModeEnabled("vie".equals(curLangCode));
        jTextArea1.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            public void mouseReleased(MouseEvent e) {
                mousePressed(e);
            }
        });
        jTextArea1.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                updateCutCopyDelete(e.getDot() != e.getMark());
            }
        });
//        jPanel1 = new javax.swing.JPanel();
//        jScrollPane2 = new javax.swing.JScrollPane();
//        jScrollPane2.getVerticalScrollBar().setUnitIncrement(20);
//        jScrollPane2.getHorizontalScrollBar().setUnitIncrement(20);
        jImageLabel = new JImageLabel();

    }// </editor-fold>//GEN-END:initComponents
    
//    private void jMenuItemHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemHelpActionPerformed
//        final String readme = myResources.getString("readme");
//        if (MAC_OS_X && new File(readme).exists()) {
//            try {
//                Runtime.getRuntime().exec(new String[]{"open", "-a", "Help Viewer", readme});
//            } catch (IOException x) {
//                x.printStackTrace();
//            }
//        } else {
//            if (helptopicsFrame == null) {
//                helptopicsFrame = new JFrame(APP_NAME + " " + myResources.getString("Help"));
//                helptopicsFrame.getContentPane().setLayout(new BorderLayout());
//                HtmlPane helpPane = new HtmlPane(readme);
//                helptopicsFrame.getContentPane().add(helpPane, BorderLayout.CENTER);
//                helptopicsFrame.getContentPane().add(helpPane.getStatusBar(), BorderLayout.SOUTH);
//                helptopicsFrame.pack();
//                helptopicsFrame.setLocation((screen.width - helptopicsFrame.getWidth()) / 2, 40);
//            }
//            helptopicsFrame.setVisible(true);
//        }
//    }//GEN-LAST:event_jMenuItemHelpActionPerformed
    
//    private void jComboBoxLangItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxLangItemStateChanged
//        if (evt.getStateChange() == ItemEvent.SELECTED) {
//            curLangCode = langCodes[jComboBoxLang.getSelectedIndex()];
//            VietKeyListener.setVietModeEnabled(curLangCode.equals("vie"));
//        }
//    }//GEN-LAST:event_jComboBoxLangItemStateChanged
    
//    private void jCheckBoxMenuWordWrapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuWordWrapActionPerformed
//        this.jTextArea1.setLineWrap(wordWrapOn = jCheckBoxMenuWordWrap.isSelected());
//    }//GEN-LAST:event_jCheckBoxMenuWordWrapActionPerformed
    
    
//    private void jMenuItemPostProcessActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPostProcessActionPerformed
//        if (curLangCode == null) return;
//        
//        try {
//            String selectedText = this.jTextArea1.getSelectedText();
//            if (selectedText != null) {
//                selectedText = Processor.postProcess(selectedText, curLangCode);
//                int start = this.jTextArea1.getSelectionStart();
//                this.jTextArea1.replaceSelection(selectedText);
//                this.jTextArea1.select(start, start + selectedText.length());
//            } else {
//                this.jTextArea1.setText(Processor.postProcess(jTextArea1.getText(), curLangCode));
//            }
//        } catch (UnsupportedOperationException uoe) {
//            uoe.printStackTrace();
//            JOptionPane.showMessageDialog(null, String.format("Post-processing not supported for %1$s language.", prop.getProperty(uoe.getMessage())), APP_NAME, JOptionPane.ERROR_MESSAGE);
//        } catch (RuntimeException re) {
//            re.printStackTrace();
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }//GEN-LAST:event_jMenuItemPostProcessActionPerformed
    
//    private void jButtonFitImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFitImageActionPerformed
//        if ((float) imageIcon.getIconWidth() / jScrollPane2.getWidth() > (float) imageIcon.getIconHeight() / jScrollPane2.getHeight()) {
//            jButtonFitWidthActionPerformed(evt);
//        } else {
//            jButtonFitHeightActionPerformed(evt);
//        }
//        reset = true;
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonFitImageActionPerformed
    
    private void jMenuItemTessPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemTessPathActionPerformed
        JFileChooser chooser = new JFileChooser(currentDirectory);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setCurrentDirectory(new File(tessPath));
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setApproveButtonText("Set");
        chooser.setDialogTitle("Locate Tesseract Directory");
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (!tessPath.equals(chooser.getSelectedFile().getAbsolutePath())) {
                tessPath = chooser.getSelectedFile().getAbsolutePath();
                logger.error("Please restart the application for the change to take effect.");
//                JOptionPane.showMessageDialog(this, "Please restart the application for the change to take effect.", APP_NAME, JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_jMenuItemTessPathActionPerformed
    
//    private void jButtonFitWidthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFitWidthActionPerformed
//        float factor = (float) imageIcon.getIconWidth() / jScrollPane2.getWidth();
//        doChange(factor, false);
//        reset = false;
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonFitWidthActionPerformed
    
//    private void jButtonFitHeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFitHeightActionPerformed
//        float factor = (float) imageIcon.getIconHeight() / jScrollPane2.getHeight();
//        doChange(factor, false);
//        reset = false;
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonFitHeightActionPerformed
    
//    private void jButtonZoomOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonZoomOutActionPerformed
//        float factor = 1.5f;
//        doChange(factor, false);
//        reset = false;
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonZoomOutActionPerformed
    
//    private void jButtonZoomInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonZoomInActionPerformed
//        float factor = 1.5f;
//        doChange(factor, true);
//        reset = false;
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonZoomInActionPerformed
    
//    void doChange(final float proportion, final boolean multiply) {
//        SwingUtilities.invokeLater(new Runnable() {
//            public void run() {
//                for (ImageIconScalable image : imageList) {
//                    int width = image.getIconWidth();
//                    int height = image.getIconHeight();
//                    
//                    if (multiply) {
//                        image.setScaledSize((int) (width * proportion), (int) (height * proportion));
//                    } else {
//                        image.setScaledSize((int) (width / proportion), (int) (height / proportion));
//                    }
//                }
//                imageIcon = imageList.get(imageIndex);
//                jImageLabel.revalidate();
//                jScrollPane2.repaint();
//                if (multiply) {
//                    originalProportion *= proportion;
//                } else {
//                    originalProportion /= proportion;
//                }
//                
//            }
//        });
//    }
//    private void jButtonOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOpenActionPerformed
//        jMenuItemOpenActionPerformed(evt);
//    }//GEN-LAST:event_jButtonOpenActionPerformed
    
//    private void jButtonOCRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOCRActionPerformed
//        jMenuItemOCRActionPerformed(evt);
//    }//GEN-LAST:event_jButtonOCRActionPerformed
    
    private void jButtonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClearActionPerformed
        this.jTextArea1.setText(null);
    }//GEN-LAST:event_jButtonClearActionPerformed
    
//    private void jButtonPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPrevActionPerformed
//        imageIndex--;
//        if (imageIndex < 0) {
//            imageIndex = 0;
//        } else {
//            this.jLabelStatus.setText(null);
//            displayImage();
//        }
//        setButton();
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonPrevActionPerformed
    
//    private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNextActionPerformed
//        imageIndex++;
//        if (imageIndex  > imageTotal - 1) {
//            imageIndex = imageTotal - 1;
//        } else {
//            this.jLabelStatus.setText(null);
//            displayImage();
//        }
//        setButton();
//        ((JImageLabel)jImageLabel).deselect();
//    }//GEN-LAST:event_jButtonNextActionPerformed
    
//    private void jMenuItemOCRAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemOCRAllActionPerformed
//        if (ImageIOHelper.getImageFile() == null) {
//            JOptionPane.showMessageDialog(this, "Please load an image.", APP_NAME, JOptionPane.INFORMATION_MESSAGE);
//            return;
//        }
//        
//        allPages = true;
//        performOCR(ImageIOHelper.getImageFile(), imageIndex);
//    }//GEN-LAST:event_jMenuItemOCRAllActionPerformed
    
//    private void jMenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAboutActionPerformed
//        JOptionPane.showMessageDialog(this, APP_NAME + ", v0.9.2 \u00a9 2007\nJava GUI Frontend for Tesseract OCR Engine\n4 May 2008\nhttp://sourceforge.net/projects/vietunicode", APP_NAME, JOptionPane.INFORMATION_MESSAGE);
//        
//    }//GEN-LAST:event_jMenuItemAboutActionPerformed
    
//    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExitActionPerformed
//        quit();
//    }//GEN-LAST:event_jMenuItemExitActionPerformed
    void quit() {
        prefs.put("currentDirectory", currentDirectory);
        prefs.put("TesseractDirectory", tessPath);
        prefs.put("inputMethod", selectedInputMethod);
        prefs.put("lookAndFeel", UIManager.getLookAndFeel().getClass().getName());
        prefs.put("fontName", font.getName());
        prefs.putInt("fontSize", font.getSize());
        prefs.putInt("fontStyle", font.getStyle());
        prefs.put("lookAndFeel", UIManager.getLookAndFeel().getClass().getName());
        prefs.putInt("windowState", getExtendedState());
//        if (this.jComboBoxLang.getSelectedIndex() != -1) {
            prefs.put("langCode", "spa");
//        }
        
        prefs.putBoolean("wordWrap", wordWrapOn);
        
        if (getExtendedState() == NORMAL) {
            prefs.putInt("frameHeight", getHeight());
            prefs.putInt("frameWidth", getWidth());
            prefs.putInt("frameX", getX());
            prefs.putInt("frameY", getY());
        }
        
//        javax.swing.filechooser.FileFilter[] filters = chooser.getChoosableFileFilters();
//        for (int i = 0; i < filters.length; i++) {
//            if (filters[i] == chooser.getFileFilter()) {
//                prefs.putInt("filterIndex", i);
//                break;
//            }
//        }
        
        System.exit(0);
    }

//    
    void saveFile(File file) {
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF8));
            jTextArea1.write(out);
            out.close();
        } catch (OutOfMemoryError oome) {
            oome.printStackTrace();
            JOptionPane.showMessageDialog(this, APP_NAME
                    + myResources.getString("_has_run_out_of_memory.\nPlease_restart_") + APP_NAME
                    + myResources.getString("_and_try_again."), myResources.getString("Out_of_Memory"), JOptionPane.ERROR_MESSAGE);
        } catch (FileNotFoundException fnfe) {
            showError(fnfe, myResources.getString("Error_saving_file_") + file + myResources.getString(".\nFile_is_inaccessible."));
        } catch (Exception ex) {
            showError(ex, myResources.getString("Error_saving_file_") + file);
        } finally {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    getGlassPane().setVisible(false);
                }
            });
        }
        
    }//GEN-LAST:event_jMenuItemSaveActionPerformed
    
//    private void jMenuItemOCRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemOCRActionPerformed
//        if (ImageIOHelper.getImageFile() == null) {
//            JOptionPane.showMessageDialog(this, "Please load an image.", APP_NAME, JOptionPane.INFORMATION_MESSAGE);
//            return;
//        }
//        
//        allPages = false;
//        
//        Rectangle rect = ((JImageLabel) jImageLabel).getRect();
//        
//        if (rect != null && jImageLabel.getIcon() != null) {
//            try {
//                ImageIcon ii = (ImageIcon) this.jImageLabel.getIcon();
//                BufferedImage bi = ((BufferedImage) ii.getImage()).getSubimage((int) (rect.x / originalProportion), (int) (rect.y / originalProportion), (int) (rect.width / originalProportion), (int) (rect.height / originalProportion));
//                File tempFile = new File(ImageIOHelper.getImageFile().getParentFile(), "tempImageFile0.tif");
//                tempFile.deleteOnExit();
//                ImageIO.write(bi, "tiff", tempFile);
//                performOCR(tempFile, 0);
//            } catch (RasterFormatException rfe) {
//                rfe.printStackTrace();
//            } catch (IOException ioe) {
//                ioe.printStackTrace();
//            }
//        } else {
//            performOCR(ImageIOHelper.getImageFile(), imageIndex);
//        }
//        
//    }//GEN-LAST:event_jMenuItemOCRActionPerformed
    
    void performOCR(final File imageFile, final int index) {
        try {
            
            String imageFileName = imageFile.getName();
            final String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
            
//            SwingUtilities.invokeLater(new Runnable() {
//
//				public void run() {
                    try {
                    	//logger.debug("OCR inicializado");
                    	
                        OCR ocrEngine = new OCR(tessPath);
//                        jTextArea1.append(ocrEngine.recognizeText(imageFile, index, allPages, imageFormat, langCodes[jComboBoxLang.getSelectedIndex()]));
                        jTextArea1.setText(ocrEngine.recognizeText(imageFile, index, allPages, imageFormat, "spa"));
                        
                        //logger.debug("OCR completado");

                        
                    } catch (OutOfMemoryError oome) {
                        oome.printStackTrace();
                        logger.error(APP_NAME
                                + myResources.getString("_has_run_out_of_memory.\nPlease_restart_") + APP_NAME
                                + myResources.getString("_and_try_again.")+ myResources.getString("Out_of_Memory"));
                    } catch (FileNotFoundException fnfe) {
                        fnfe.printStackTrace();
                        logger.error( "An exception occurred in Tesseract engine while recognizing this image.");
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                        logger.error( "Cannot find Tesseract. Please set its path.");
                    } catch (RuntimeException re) {
                        re.printStackTrace();
                        logger.error(re.getMessage());
                    } catch (Exception exc) {
                        exc.printStackTrace();
                    }
//                }
//            });
            
        } catch (Exception exc) {
            logger.error(exc.getMessage());
        } 
//        finally {
//            SwingUtilities.invokeLater(new Runnable() {
//                public void run() {
//                    getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
//                    getGlassPane().setVisible(false);
//                	
//                }
//
//            });
//        }
        
    }
    
//    private void jMenuItemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemOpenActionPerformed
//        
//        int returnVal = chooser.showOpenDialog(this);
//        if (returnVal == JFileChooser.APPROVE_OPTION) {
//            currentDirectory = chooser.getCurrentDirectory().getPath();
//            openFile(chooser.getSelectedFile());
//            originalProportion = 1f;
//        }
//    }//GEN-LAST:event_jMenuItemOpenActionPerformed
    
//    /**
//     *  Updates UI component if changes in LAF
//     *
//     *@param  laf  the look and feel class name
//     */
//    protected void updateLaF(String laf) {
//        try {
//            UIManager.setLookAndFeel(laf);
//        } catch (Exception exc) {
//            // do nothing
//            exc.printStackTrace();
//        }
//        SwingUtilities.updateComponentTreeUI(this);
//        SwingUtilities.updateComponentTreeUI(popup);
//        SwingUtilities.updateComponentTreeUI(chooser);
//    }
    
    /**
     * Opens image file.
     *
     */
    public void openFile(File selectedFile) {
//        this.setTitle(selectedFile.getName() + " - " + APP_NAME);
        loadImage(selectedFile);
        /*Puede comentarse*/
//		        displayImage();
//		        jLabelStatus.setText(null);
//		        ((JImageLabel)jImageLabel).deselect();
//		        
//		        this.jButtonFitHeight.setEnabled(true);
//		        this.jButtonFitImage.setEnabled(true);
//		        this.jButtonFitWidth.setEnabled(true);
//		        this.jButtonZoomIn.setEnabled(true);
//		        this.jButtonZoomOut.setEnabled(true);
//		        
//		        if (imageList.size() == 1) {
//		            this.jButtonNext.setEnabled(false);
//		            this.jButtonPrev.setEnabled(false);
//		        } else {
//		            this.jButtonNext.setEnabled(true);
//		            this.jButtonPrev.setEnabled(true);
//		        }
//		        
//		        setButton();
		/*Puede comentarse*/
    }
    
//    void displayImage() {
//        if (imageList != null) {
//            this.jLabelCurIndex.setText("Page " + (imageIndex + 1) + " of " + imageTotal);
//            imageIcon = imageList.get(imageIndex);
//            jImageLabel.setIcon(imageIcon);
//            jImageLabel.revalidate();
//        }
//    }
    
//    void setButton() {
//        if (imageIndex == 0) {
//            this.jButtonPrev.setEnabled(false);
//        } else {
//            this.jButtonPrev.setEnabled(true);
//        }
//        
//        if (imageIndex == imageList.size() - 1) {
//            this.jButtonNext.setEnabled(false);
//        } else {
//            this.jButtonNext.setEnabled(true);
//        }
//    }
    
    void loadImage(File selectedFile) {
        try {
            imageList = ImageIOHelper.getImageList(selectedFile);
            imageTotal = imageList.size();
            imageIndex = 0;
        } catch (NoClassDefFoundError ncde) {
            logger.error("Required JAI Image I/O Library is not found. ",ncde);
        }
    }
    
//    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
//        jSplitPane1.setDividerLocation(jSplitPane1.getWidth() / 2);
//        
//        if (reset && ImageIOHelper.getImageFile() != null) {
//            SwingUtilities.invokeLater(new Runnable() {
//                public void run() {
//                    jButtonFitImageActionPerformed(null);
//                }
//            });
//        }
//    }//GEN-LAST:event_formComponentResized
    
    /**
     *  Shows a warning message
     *
     *@param  e        the exception to warn about
     *@param  message  the message to display
     */
    public void showError(Exception e, String message) {
        logger.error(APP_NAME+": "+ message);

    }
    
//    private int snap(final int ideal, final int min, final int max) {
//        final int TOLERANCE = 0;
//        return ideal < min + TOLERANCE ? min : (ideal > max - TOLERANCE ? max : ideal);
//    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
    		PropertyConfigurator.configure("log4j.properties");
            UtilsOCR.loadProperties(); 
            Gui gui=new Gui();
            logger.info("Comenzando a leer documentos....");
            gui.TimerDirectory();
//            gui.setVisible(true);
          
            }
        });
    }
    
    /**
     * Lanza un timer, avisando a los observadores de este
     * modelo del cambio. 
     */
    public void TimerDirectory(){
            	logger.info("============Lectura de Directorio almacenamiento Temporal de los CORREOS========");
            	//System.out.println("============Lectura de Directorio Temporal========");
            	directoryTemporalAdjuntos=new File(UtilsOCR.getPropertiesPaths().getProperty("DIRECTORIO_TEMPORAL"));
				File[] ficheros=directoryTemporalAdjuntos.listFiles();
				if(ficheros!=null){
					for (File file : ficheros) {
						if(!file.getName().equals("Desconocidos")){
							try {
								String operacion="Correo";
								checkDirectory(file,operacion);
							} catch (NumberFormatException e1){
								logger.error(e1);
							} catch (SQLException e1) {
								logger.error(e1);
							} catch (ParseException e1) {
								logger.error(e1);
							}
						}
					}
				}else{
					logger.error("El Directorio de Lectura est� mal configurado");
					getTimer().stop();
					  quit();
				}

     }
    
    public void TimerDirectoryEscaneos(){
//        timer = new Timer (2*60*1000,new ActionListener ()//1000ms=1s
//        {
        	
//            public void actionPerformed(ActionEvent e)
//            {
//            	long inicio=System.currentTimeMillis();
            	logger.info("============Lectura de Directorio Escaneos========");
            	//System.out.println("============Lectura de Directorio========");
            	directoryEscaneos=new File(UtilsOCR.getPropertiesPaths().getProperty("ESCANEOS_DIR_PATH"));
				File[] ficheros=directoryEscaneos.listFiles();
				if(ficheros!=null){
					for (File file : ficheros) {
						if(!file.getName().equals("Analizados")&&!file.getName().equals("Pendientes")&&!file.getName().equals("Validados")&&!file.getName().equals("Desconocidos")){
							try {
								String operacion="Escaner";
								checkDirectory(file,operacion);
							} catch (NumberFormatException e1){
								logger.error(e1);
							} catch (SQLException e1) {
								logger.error(e1);
							} catch (ParseException e1) {
								logger.error(e1);
							}
						}
					}
				}else{
					logger.error("El Directorio de Lectura está mal configurado");
					getTimer().stop();
					  quit();
				}
//				long fin=System.currentTimeMillis();
//				long tiempoTotal=fin-inicio;
//            	System.out.println ("Tiempo en procesar un fichero de "filesource.length()+" es "+tiempoTotal+" ms");

            }


 //       });
 //       setTimer(timer);
 //       getTimer().start();
 //   }
    
    
    private void altaAlerta(Connection conn,String directoryParent, String directoryName, String fileName,String origen,ArrayList<DictionaryWord> palabrasClave, int idRole) throws SQLException {
    	
    	//conseguir el numero de documentos
		AlertasLN alertLN=new AlertasLN();
		
	    String dateFormat = "dd-MM-yyyy HH:mm:ss:SSS";
	    DateFormat df = new SimpleDateFormat(dateFormat);
	 
	    String dateTime = df.format(new Date().getTime());
	    
		String palabrasClaveString="";

    	if(directoryParent!=null&& directoryName!=null &&!directoryParent.equals("") && !directoryName.equals("")){

			ArrayList<String>usernames=new ArrayList<String>();
			
			String sql = "SELECT USER_FOLDER.USERNAME" +
						  " FROM USER_FOLDER" +
						  " WHERE USER_FOLDER.ID_FOLDER=(SELECT ID_FOLDER FROM FOLDERS WHERE DIRECTORYPARENT=?" +
						  " AND DIRECTORYNAME=?)";
		        
			PreparedStatement stmt = null;
	
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, directoryParent);
			stmt.setString(2, directoryName);
			
			ResultSet rs=stmt.executeQuery();
			
			while (rs.next()) {
				String username = (String) rs.getString("USERNAME");
				usernames.add(username);
			}
	
			rs.close();
			stmt.close();
						
			for (int i = 0; i < palabrasClave.size(); i++) {
				DictionaryWord dictionaryWord = palabrasClave.get(i);
				if(!palabrasClaveString.contains(dictionaryWord.getKeyWord()))
					palabrasClaveString+=dictionaryWord.getKeyWord()+", ";
			}
			
			for (String username : usernames) {	
				alertLN.insertarAlerta(getConnection(),username,directoryParent,directoryName,dateTime,fileName,origen,palabrasClaveString,idRole);
			}
    	}else{
    		//No hay destinatarios
			alertLN.insertarAlerta(getConnection(),null,directoryParent,directoryName,dateTime,fileName,origen,palabrasClaveString,idRole);
    	}

	}
    
	private void insertRole(String newNombreUsuario,String role) throws SQLException {
		 PreparedStatement stmt = getConnection().prepareStatement(getSQLInsertUserRoles());
	     stmt.setString(1, newNombreUsuario);
	     stmt.setString(2, role);
	     
	     stmt.executeQuery();
	     stmt.close();
		
	}
	private String getSQLInsertUserRoles() {
		String 	sql= "INSERT INTO USER_ROLES (USERNAME,ID_ROLE) VALUES (?,?)";
		return sql;
	}
    
    private Connection getConnection() throws SQLException {
		Connection conn = null;
		conn = UtilsOCR.connectionOracleGestDocsBBDD();
        if(conn==null){
            System.out.println("Conexi�n fallida");
        }
        return conn;
	}
    
    /**
     * Elimina la imagen creada del pDF
     */
    private void removeImage() {
    	if(ImageIOHelper.getImageFile()!=null){
		  if (ImageIOHelper.getImageFile().exists()) {
			 // logger.debug("Elimina la imagen creada");
			  if(!ImageIOHelper.getImageFile().delete()){
				logger.error("El fichero "+ImageIOHelper.getImageFile().getName()+" no puede eliminarse");
			  }
		  }
    	}
	}
    
    /**
     * Chacked Sequence palabrasCalve
     * @param palabrasClave
     * @return true if any charsequence is found else false
     */
    private boolean checkSequences(ArrayList<DictionaryWord>palabrasClave) {
    	boolean encontrada=false;
    	
    	for (int i = 0; i < palabrasClave.size()-1; i++) {
    		DictionaryWord  dictionaryWord= palabrasClave.get(i);
    		if(jTextArea1.getText().toUpperCase().contains(dictionaryWord.getKeyWord())){
  			  encontrada=true;
  			  palabrasClaveEncontradas.add(dictionaryWord);
  		  }
		}    	
		return encontrada;
	}
    
	private void analyzeResult(String operacion) throws SQLException {
	        	String sql = "SELECT * FROM DICTIONARY ";
	        	PreparedStatement stmt = getConnection().prepareStatement(sql);
	        	ResultSet rset = stmt.executeQuery();	              
	            ArrayList<DictionaryWord>palabrasClave=new ArrayList<DictionaryWord>();
	            DictionaryWord dictionaryWord=null;
	            String oldDestino="",oldParent="";
	            
	            while(rset.next()){
	            	dictionaryWord=new DictionaryWord();
	            	dictionaryWord.setKeyWord(rset.getString("KEYWORD"));
	            	dictionaryWord.setId_role(rset.getInt("ID_ROLE"));
	            	dictionaryWord.setIdFolder(rset.getInt("ID_FOLDER"));
	            	
	            	palabrasClave.add(dictionaryWord);
	            }          
	            rset.close();
	            stmt.close();
	            
	            if(checkSequences(palabrasClave))		//<<<<--------falla aqui
	            {
	            	for (DictionaryWord dictionaryWordEncontrado : palabrasClaveEncontradas) {	  			
		  	  			sql = "SELECT DIRECTORYPARENT,DIRECTORYNAME FROM FOLDERS WHERE ID_FOLDER=?";
		  	  			stmt = getConnection().prepareStatement(sql);
		  	  			stmt.setInt(1, dictionaryWordEncontrado.getIdFolder());
		        		rset = stmt.executeQuery();
	        		  			  	
		        		if(rset.next()){       	
			        		String directoryParent=rset.getString("DIRECTORYPARENT");
		  	  				String directoryName=rset.getString("DIRECTORYNAME");
	
			  			  	try {
			  			  		
			  			  		if(operacion.equals("Correo")){	//------operaciones a realizar si llamamos a este metodo desde el lector de correos
			  			  			String origen=UtilsOCR.getPropertiesPaths().getProperty("DIRECTORIO_TEMPORAL")+File.separator+filesource.getName(); 
			  			  			String destino=UtilsOCR.getPropertiesPaths().getProperty("DESTINATION_DIR_PATH")+File.separator+directoryParent+File.separator+directoryName+File.separator+filesource.getName();
			  			        
				  			        if(!oldDestino.equals(destino)){
				  			        		logger.info("se han encontrado palabras clave, el documento se copiara a la carpeta "+destino);
				  			        		UtilsOCR.fileCopy(origen,destino);
				  			        		//la base de datos esta limitada a nombres de fichero de un maximo de 50 caractares, por lo que si los excede hay que renombrarlo
				  			        		if(filesource.getName().length()>50){
					  			        		altaAlerta(getConnection(),directoryParent,directoryName,UtilsOCR.ranameBigNamedDocument(filesource.getName()),directoryTemporalAdjuntos.equals(filesource.getParentFile())?directoryTemporalAdjuntos.getName():directoryTemporalAdjuntos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,dictionaryWordEncontrado.getId_role());
				  			        		}
				  			        		else{
					  			        		altaAlerta(getConnection(),directoryParent,directoryName,filesource.getName(),directoryTemporalAdjuntos.equals(filesource.getParentFile())?directoryTemporalAdjuntos.getName():directoryTemporalAdjuntos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,dictionaryWordEncontrado.getId_role());
				  			        		}
				  			        }
				  			        if(!oldParent.equals(directoryParent)){
				  			        	logger.info("movemos el documento a la carpeta compartida correspondiente");
			  			        		moveDocumentToSharedFolder(directoryParent,dictionaryWordEncontrado.getId_role());	//llamamos al metodo, que inserte el documento en la carpeta compartida correspondiente
				  			        }
				  			        oldParent=directoryParent;
				  			        oldDestino=destino;
			  			  		}
			  			  		else{		//operaciones a realizar si llamamos a este metodo desde el analizador de documentos escneados
			  			  			String origen=directoryEscaneos.getAbsolutePath()+File.separator+(directoryEscaneos.equals(filesource.getParentFile())?filesource.getName():filesource.getParentFile().getName()+File.separator+filesource.getName()); 
			  			  			String destino=UtilsOCR.getPropertiesPaths().getProperty("ESCANEOS_DIR_PATH")+File.separator+"Analizados"+File.separator+filesource.getName();
			  			  			UtilsOCR.fileMove(origen,destino);
				  			  		if(filesource.getName().length()>50){
			  			        		altaAlerta(getConnection(),directoryParent,directoryName,UtilsOCR.ranameBigNamedDocument(filesource.getName()),directoryTemporalAdjuntos.equals(filesource.getParentFile())?directoryTemporalAdjuntos.getName():directoryTemporalAdjuntos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,dictionaryWordEncontrado.getId_role());			  			  			
				  			  		}
				  			  		else{
			  			        		altaAlerta(getConnection(),directoryParent,directoryName,filesource.getName(),directoryTemporalAdjuntos.equals(filesource.getParentFile())?directoryTemporalAdjuntos.getName():directoryTemporalAdjuntos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,dictionaryWordEncontrado.getId_role());			  			  			
				  			  		}
			  			  		}
			  				} catch (Exception e) {
			  					logger.error("error al mover el documento "+e.getMessage());
			  				}
		        		}
		        		  rset.close();
		                  stmt.close();
	            	}
	            }
	            else{
	            	try{
	            		if(operacion.equals("Correo")){
		            		String origen=UtilsOCR.getPropertiesPaths().getProperty("DIRECTORIO_TEMPORAL")+File.separator+filesource.getName(); 
		  			        String destino=UtilsOCR.getPropertiesPaths().getProperty("DIRECTORIO_TEMPORAL")+File.separator+"Desconocidos"+File.separator+filesource.getName(); 
		  			        logger.info("No se han econtrado palabras clave, el documento se movera a la carpeta Temporal/Desconocidos");	  			        
			  			    UtilsOCR.fileMove(origen,destino);
			  			    if(filesource.getName().length()>50){
				   			    altaAlerta(getConnection(),null,null,UtilsOCR.ranameBigNamedDocument(filesource.getName()),directoryTemporalAdjuntos.equals(filesource.getParentFile())?directoryTemporalAdjuntos.getName():directoryTemporalAdjuntos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,0);
			  			    }
			  			    else{
				   			    altaAlerta(getConnection(),null,null,filesource.getName(),directoryTemporalAdjuntos.equals(filesource.getParentFile())?directoryTemporalAdjuntos.getName():directoryTemporalAdjuntos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,0);
			  			    }
	            		}
	            		else{
	            			logger.info("No se han encontrado palabras clave para el documento, se movera a la carpeta Desconocidos");
	  			  			String origen=directoryEscaneos.getAbsolutePath()+File.separator+(directoryEscaneos.equals(filesource.getParentFile())?filesource.getName():filesource.getParentFile().getName()+File.separator+filesource.getName()); 
	  			  			String destino=UtilsOCR.getPropertiesPaths().getProperty("ESCANEOS_DIR_PATH")+File.separator+"Desconocidos"+File.separator+filesource.getName();
	  			  			UtilsOCR.fileMove(origen, destino);
	  			  			if(filesource.getName().length()>50){
		  			  			altaAlerta(getConnection(),null,null,UtilsOCR.ranameBigNamedDocument(filesource.getName()),directoryEscaneos.equals(filesource.getParentFile())?directoryEscaneos.getName():directoryEscaneos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,0);
	  			  			}else{
		  			  			altaAlerta(getConnection(),null,null,filesource.getName(),directoryEscaneos.equals(filesource.getParentFile())?directoryEscaneos.getName():directoryEscaneos.getName()+"\\"+filesource.getParentFile().getName(),palabrasClaveEncontradas,0);
	  			  			}
	            		}
	            	}catch(Exception e){
	            		logger.error("error al mover el documento "+e.getMessage());
	            	}
	            }
	            releaseConnection();
	            palabrasClaveEncontradas.clear();   
    }

	
	
	private boolean moveDocumentToSharedFolder(String directoryParent,int role) throws SQLException{
		boolean moved=false;
		PreparedStatement stmt =null;
		ResultSet rs=null;
		String directoryParentShared=null,directoryName=null;
		String sql="SELECT DIRECTORYPARENT, DIRECTORYNAME FROM FOLDERS WHERE DIRECTORYPARENT = ? AND SHARED = 1";

		stmt = getConnection().prepareStatement(sql);
		stmt.setString(1, directoryParent);
		rs = stmt.executeQuery();

		if (rs.next()) {
			directoryParentShared = rs.getString("DIRECTORYPARENT");
			directoryName = rs.getString("DIRECTORYNAME");
		}

		String origen = UtilsOCR.getPropertiesPaths().getProperty("DIRECTORIO_TEMPORAL")+ File.separator + filesource.getName();
		String destino = UtilsOCR.getPropertiesPaths().getProperty(
				"DESTINATION_DIR_PATH")+ File.separator+ directoryParentShared+ File.separator+ directoryName + File.separator + filesource.getName();
		if (UtilsOCR.fileMove(origen, destino)) {
			moved = true;
			altaAlerta(getConnection(),directoryParent,directoryName,filesource.getName(),directoryTemporalAdjuntos.equals(filesource.getParentFile()) ? directoryTemporalAdjuntos.getName() : directoryTemporalAdjuntos.getName()+ "\\" + filesource.getParentFile().getName(),palabrasClaveEncontradas, role);
		}

		return moved;
	}
	
	private void releaseConnection() throws SQLException {
		getConnection().close();
		
	}

	public void checkDirectory(File directorio,String operacion) throws NumberFormatException, SQLException, ParseException {
			
			if(directorio.isDirectory()){
				logger.debug("Analizamos el directorio "+directorio.getName());		

				for (int i = 0; i < directorio.listFiles().length; i++)	
				{

					File file=directorio.listFiles()[i];
						if(file.isDirectory()){
							logger.debug("Analizamos el directorio "+file.getName());		
							checkDirectory(file, operacion);
						}else{
							if(file.getName().endsWith("pdf")){
								filesource=file;
								logger.info("Documento: "+filesource.getName()+" para analizar.");
								if(filesource.length()<Integer.parseInt(UtilsOCR.getPropertiesPaths().getProperty("MAXSIZEFILE"))){
								  openFile(filesource);
								  originalProportion = 1f;
								  performOCR(ImageIOHelper.getImageFile(), imageIndex);
								}else{
									logger.debug("El fichero "+filesource.getName()+" no ha sido analizado porque su tama�o excede de 1MB");

								}
								try {
									analyzeResult(operacion);	
								} catch (SQLException e1) {
								  logger.error("Error de BBDD", e1);
								}
								 removeImage();		
							}							
						}	
				}
			}else{
				if(directorio.getName().endsWith("pdf") || directorio.getName().endsWith("png") || directorio.getName().endsWith("jpeg") || directorio.getName().endsWith("jpg")
						|| directorio.getName().endsWith("PNG") || directorio.getName().endsWith("JPEG") || directorio.getName().endsWith("JPG") ){
					
					//si el archivo contiene espacio en blanco, no se podra mover o copiar, aqui se eliminan esos espacios----
					if(directorio.getName().contains(" ")){
						try{
							logger.info("el nombre del fichero tiene espacios, por lo que no es valido y se renombrara");
							String newName=directorio.getName().replace(" ", "");
							String newPath=directorio.getAbsolutePath().replace(directorio.getName(), newName);	
							File newFile=new File(newPath);
							FileUtils.moveFile(directorio, newFile);
							directorio=newFile;
						}
						catch(IOException ioe){
							logger.error("error "+ioe);
						}
					}
					//---------------------------------------------------------------------------
					logger.info("---->Analizamos el fichero "+directorio.getName());	
					filesource=directorio;
					if(filesource.length()<Integer.parseInt(UtilsOCR.getPropertiesPaths().getProperty("MAXSIZEFILE"))){
						  openFile(filesource);
						  originalProportion = 1f;
						  performOCR(ImageIOHelper.getImageFile(), imageIndex);
						}else{
							logger.debug("El fichero "+filesource.getName()+" no ha sido analizado porque su tama�o excede de 1MB");

						}
						try {
							analyzeResult(operacion);	
						} catch (SQLException e1) {
						  logger.error("Error de BBDD", e1);
						}
						removeImage();
				}
			}	
	}
    

	// Variables declaration - do not modify//GEN-BEGIN:variables
//    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuWordWrap;
//    private javax.swing.JComboBox jComboBoxLang;
    private javax.swing.JLabel jImageLabel;
//    private javax.swing.JLabel jLabelCurIndex;

    private javax.swing.JTextArea jTextArea1;

    private javax.swing.JPopupMenu popup;
    // End of variables declaration//GEN-END:variables
    private final UndoManager m_undo = new UndoManager();
    private final UndoableEditSupport undoSupport = new UndoableEditSupport();
    private Action m_undoAction, m_redoAction, actionCut, actionCopy, actionPaste, actionDelete, actionSelectAll;
    private final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

	public Timer getTimer() {
		return timer;
	}

	public void setTimer(Timer timer) {
		this.timer = timer;
	}
        
}


